package com.jwtproject.bootserver.security.handler;


import com.jwtproject.bootserver.status.StatusCode;
import com.jwtproject.bootserver.status.SystemStatusEnum;
import com.jwtproject.bootserver.util.UtilResponse;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description：自定义登录失败处理类
 **/
@Slf4j
public class SecurityAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        //用户名或密码错误
        if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
            UtilResponse.writeFailureResult(response, SystemStatusEnum.USERNAME_PASSWORD_ERROR.code, "用户名或密码错误");
        } else if (e instanceof LockedException) { //账号被锁定
            UtilResponse.writeFailureResult(response, SystemStatusEnum.ACCOUNT_LOCKED.code, SystemStatusEnum.ACCOUNT_LOCKED.desc);
        } else if (e instanceof DisabledException) { //账户被禁用
            UtilResponse.writeFailureResult(response, SystemStatusEnum.ACCOUNT_DISABLE.code, SystemStatusEnum.ACCOUNT_DISABLE.desc);
        } else if (e instanceof AccountExpiredException) { //账户已过期
            UtilResponse.writeFailureResult(response, SystemStatusEnum.ACCOUNT_EXPIRED.code, SystemStatusEnum.ACCOUNT_EXPIRED.desc);
        } else if (e instanceof CredentialsExpiredException) { //密码已过期
            UtilResponse.writeFailureResult(response, SystemStatusEnum.PASSWORD_EXPIRED.code, SystemStatusEnum.PASSWORD_EXPIRED.desc);
        } else {
            UtilResponse.writeFailureResult(response, StatusCode.INTERNAL_SYSTEM_ERROR, "系统异常，登录失败！");
        }

    }
}
